package com.example.xpath;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;

public class XpathTest {

	private String htmlPath = System.getProperty("user.dir") + "/src/main/java/com/example/xpath/viewReport.htm";

	public static void main(String[] args) throws Exception {
		XpathTest xTest = new XpathTest();
//		String partContent = xTest.splitHtml();
//		xTest.parse(partContent);
		String recourseHtml = xTest.test();
		xTest.recourseParse(recourseHtml);
	}

	public void recourseParse(String recourseHtml) {
		JXDocument jxd = JXDocument.create(recourseHtml);
		List<JXNode> recourseList = jxd.selN("//table");
		for (int i = 0; i < recourseList.size(); i++) {
			JXNode node = recourseList.get(i);
			if (i % 2 == 0) {
				String governOrg = node.selOne("./tbody/tr[2]/td[1]/text()").asString(); // 管理机构
				System.out.println(governOrg);
				String businessType = node.selOne("./tbody/tr[2]/td[2]/text()").asString(); // 业务种类
				System.out.println(businessType);
				String receivedDate = node.selOne("./tbody/tr[2]/td[3]/text()").asString(); // 债权接收日期
				System.out.println(receivedDate);
				String claimAmount = node.selOne("./tbody/tr[2]/td[4]/text()").asString(); // 债权金额
				System.out.println(claimAmount);
				String claimStatus = node.selOne("./tbody/tr[2]/td[5]/text()").asString(); // 债权转移时的还款状态
				System.out.println(claimStatus);
			} else {
				String deadline = node.selOne("./tbody/tr[1]/th/text()").asString(); // 截止日期
				System.out.println(deadline);
				String accountStatus = node.selOne("./tbody/tr[3]/td[1]/text()").asString(); // 账户状态
				System.out.println(accountStatus);
				String accountBalance = node.selOne("./tbody/tr[3]/td[2]/text()").asString(); // 余额
				System.out.println(accountBalance);
				String lastRepaymentDate = node.selOne("./tbody/tr[3]/td[3]/text()").asString(); // 最近一次还款日期
				System.out.println(lastRepaymentDate);
			}
		}
	}

	public String test() {
		StringBuilder builder = new StringBuilder();
		Path htmlFilePath = Paths.get(htmlPath);
		String htmlContent = null;
		try (BufferedReader reader = Files.newBufferedReader(htmlFilePath)) {
			htmlContent = reader.lines().collect(Collectors.joining("\n"));
		} catch (IOException e) {
			e.printStackTrace();
			return builder.toString();
		}
		String regex = "<DIV class=\"t2 f-mgtop\">（一）被追偿信息</DIV>(.*?)<DIV class=\"t2 f-mgtop\">（二）非循环贷账户</DIV>";
		Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(htmlContent);
		while (matcher.find()) {
			String matchedContent = matcher.group(1).replace("</DIV>", "");
			builder.append(matchedContent);
		}
		return builder.toString();
	}

	public void parse(String html) throws IOException {
		// File input = new File(htmlPath);
		// 注意：这里使用了xmlParser()，因为HTML可能是不规则的，但这可能会影响到HTML标签的解析。如果HTML比较标准，可以考虑使用HtmlParser.htmlParser()
		// Document doc = Jsoup.parse(input, "UTF-8", "", Parser.xmlParser());
		// JXDocument jxd = JXDocument.create(doc);
		JXDocument jxd = JXDocument.create(html);
		JXNode reportNumber = jxd.selNOne("//body/table[1]//tr[1]/td[1]/text()");
		System.out.println(reportNumber.toString().replace("报告编号：", ""));
		JXNode reportTime = jxd.selNOne("//body/table[1]//tr[1]/td[2]/text()");
		System.out.println(reportTime.toString().replace("报告时间：", ""));
		List<JXNode> queriedPersonInfoList = jxd.selN("//body/table[1]//tr[position() >= 3]");
		for (JXNode node : queriedPersonInfoList) {
			String queriedPersonName = node.selOne("./td[1]/text()").toString();
			System.out.println(queriedPersonName);
			String queriedPersonIdType = node.selOne("./td[2]/text()").toString();
			System.out.println(queriedPersonIdType);
			String queriedPersonIdNumber = node.selOne("./td[3]/text()").toString();
			System.out.println(queriedPersonIdNumber);
			String queryingOrganization = node.selOne("./td[4]/text()").toString();
			System.out.println(queryingOrganization);
			String queryReason = node.selOne("./td[5]/text()").toString();
			System.out.println(queryReason);
		}
		JXNode userDisputePrompt = jxd.selNOne("//body/table[2]/tbody/tr[2]/td/text()");
		System.out.println(userDisputePrompt.toString());
	}

	public String splitHtml() {
		StringBuilder builder = new StringBuilder();
		Path htmlFilePath = Paths.get(htmlPath);
		String htmlContent = null;
		try (BufferedReader reader = Files.newBufferedReader(htmlFilePath)) {
			htmlContent = reader.lines().collect(Collectors.joining("\n"));
		} catch (IOException e) {
			e.printStackTrace();
			return builder.toString();
		}
		String regex = "<H3 class=\"u-repver\">（授信机构版）</H3></DIV>(.*?)<DIV class=\"m-repbody\">";
		Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(htmlContent);
		while (matcher.find()) {
			String matchedContent = matcher.group(1).replace("</DIV>", "");
			builder.append(matchedContent);
		}
		return builder.toString();
	}

}
